package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.constant.MqConst;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 *  支付宝
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    //统一收单下单并支付页面接口
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String  submit(@PathVariable(name = "orderId") Long orderId){
        //支付宝公司提供一个支付完整的页面  以字符串形势返回的
        return alipayService.submit(orderId);
    }

    //同步回调请求
    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }
    //异步接收
    @ResponseBody
    @PostMapping("/callback/notify")  //将异步通知中收到的所有参数都存放到map中
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){
        System.out.println("异步接收成功");
        System.out.println(paramsMap);

        //{gmt_create=2020-09-16 15:15:53,
        // charset=utf-8,
        // gmt_payment=2020-09-16 15:16:05,
        // notify_time=2020-09-16 15:16:05,
        // subject=Apple iPhone 11 (A2223) 256GB 红色 移动联通电信4G手机 双卡双待 三星 Galaxy S10(SM-G9730)骁龙855超感屏 超声波屏下指纹 4G手机 全网通 双卡,
        // sign=uVqci3GKQgLNPhyWKiRzi5j1R6yxI3RUYmsYJQZBoRbcxJuVDBqYSjQ3pb5R4Wu0ljRLvr8+bKynEuIb+9T/nOn2akO7Zt3VFpzeOECOTXZ+XU4dlkoYv9/DJy0RAlmpZvSHhnKBkF42v/BqGJ46g9T26WxrMiS5ItdVvP4el9paPt2bvHrKIyEAIasfDmR5wgDANTFj0a3fk7e8KXeYeGLd3Hs1OLTRVRrafUlH9MoJ9yxb5l+nqC7tyOtvGdoOikQskWCnHAf4NHUyQLkdanJ0TBsekvQdXeSWDCRA9LlXikJYu+DK7f8qUlZe1KuDfjNHwsHpOYYkLhzOsieSBg==,
        // buyer_id=2088102181130586,
        // invoice_amount=10498.00,
        // version=1.0,
        // notify_id=2020091600222151605030580510014052,
        // fund_bill_list=[{"amount":"10498.00","fundChannel":"ALIPAYACCOUNT"}],
        // notify_type=trade_status_sync,
        // out_trade_no=ATGUIGU16002405354063,
        // total_amount=10498.00,
        // trade_status=TRADE_SUCCESS,
        // trade_no=2020091622001430580501227373,
        // auth_app_id=2016102100732915,
        // receipt_amount=10498.00,
        // point_amount=0.00,
        // app_id=2016102100732915,
        // buyer_pay_amount=10498.00,
        // sign_type=RSA2,
        // seller_id=2088102180533564}

        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    AlipayConfig.alipay_public_key, AlipayConfig.charset,
                    AlipayConfig.sign_type); //调用SDK验证签名
            if(signVerified){
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                //1:再次校验 钱的数量是否正确
                //2:交易状态是否为成功
                if("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))){
                    //3:更新支付表中（幂等性问题）   流水号  / 支付状态 、回调时间  、回调内容
                    paymentService.updatePayment(paramsMap);

                }

                //4: 订单状态？ 扣库存？ 仓库那边 折单   昌平区  大兴区
                return "success";
            }else{
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                System.out.println(paramsMap);
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }




}
